#pragma once

#include "Object.h"

class WindMill : public Object
{
private:
	float fanTheta;
	float fanSpeed;

	void setPoleColorMaterial()
	{
		GLfloat mat_ambient[] = {0.4f, 0.4f, 0.4f, 1.0f};
		GLfloat mat_diffuse[] = {0.4f, 0.4f, 0.4f, 1.0f};
		GLfloat mat_specular[] = {0.2f, 0.2f, 0.2f, 1.0f};
		GLfloat mat_shininess[] = {5.0f};
		glMaterialfv(GL_FRONT,GL_AMBIENT,mat_ambient);
		glMaterialfv(GL_FRONT,GL_DIFFUSE,mat_diffuse);
		glMaterialfv(GL_FRONT,GL_SPECULAR,mat_specular);
		glMaterialfv(GL_FRONT,GL_SHININESS,mat_shininess);
	}

	void setFanColorMaterial()
	{
		GLfloat mat_ambient[] = {1.0f, 0.2f, 0.2f, 1.0f};
		GLfloat mat_diffuse[] = {1.0f, 0.2f, 0.2f, 1.0f};
		GLfloat mat_specular[] = {1.0f, 0.2f, 0.2f, 1.0f};
		GLfloat mat_shininess[] = {5.0f};
		glMaterialfv(GL_FRONT,GL_AMBIENT,mat_ambient);
		glMaterialfv(GL_FRONT,GL_DIFFUSE,mat_diffuse);
		glMaterialfv(GL_FRONT,GL_SPECULAR,mat_specular);
		glMaterialfv(GL_FRONT,GL_SHININESS,mat_shininess);
	}

	void drawPole()
	{
		float height = 0.8;
		float radius = .02;

		setPoleColorMaterial();

		glPushMatrix();
		GLUquadricObj *pole;
		pole = gluNewQuadric();
		glRotatef(-90, 1, 0, 0);
		gluCylinder(pole, radius, radius, height, 32, 32);
		glPopMatrix();

		// Top of pole
		glPushMatrix();
		glTranslated(0,height,0);
		glutSolidCube(radius*2);
		glPopMatrix();

		// Knob that fan hooks into
		glPushMatrix();
		glTranslated(0,height,0);
		glScaled(1,1,1.5);
		glTranslated(0,0,radius);
		glutSolidSphere(radius,10,10);
		glPopMatrix();
	}

	void drawFan()
	{
		float bladeLength = 0.2;
		float numOfBlades = 20;

		setFanColorMaterial();
		glTranslated(0, .8, .04);	// Get to the center of the knob

		for (int i = 0; i < numOfBlades; i++)
		{
			glPushMatrix();

			// Rotation from update()
			glRotated(-fanTheta, 0, 0, 1);

			// Rotation for each blade
			glRotated(i * (360/numOfBlades), 0, 0, 1);
			// Blade of fan
			glBegin(GL_TRIANGLES);
				glVertex3f(0, 0, 0);
				glVertex3f(0.01, bladeLength, 0.01);
				glVertex3f(-0.01, bladeLength, -0.01);
			glEnd();

			glPopMatrix();
		}
	}

public:
	WindMill(float x, float y, float z, float size, float fanSpeed)
	{
		fanTheta = 0;
		setPosition(x, y, z);
		setSize(size);
		setFanSpeed(fanSpeed);
	}
	
	void setFanTheta(float fanTheta) { this->fanTheta = fanTheta; }
	float getFanTheta() { return fanTheta; }

	void setFanSpeed(float fanSpeed) { this->fanSpeed = fanSpeed; }
	float getFanSpeed() { return fanSpeed; }

	void draw()
	{
		glPushMatrix();

		// Transformations
		glScaled(size,size,size);
		glTranslated(position.x, position.y, position.z);
		glRotatef(rotation, 0, 1, 0);

		drawPole();

		drawFan();

		glPopMatrix();
	}

	void update(float delta)
	{
		fanTheta += fanSpeed * delta * 16;
		if (fanTheta >= 360) { fanTheta -= 360; }
	}
};
